<template>
  <ve-card title="客户信息" :customContentStyle="{ paddingBottom: 0 }" v-bind="$attrs">
    <template #forever-show="{ contentIsShow }">
      <ve-form-item label="客户类型" class="memeber-type-form">
        <template v-if="mode == 'edit'">
          <text style="color: #cdced0">{{ form.memberTypeName }}</text>
        </template>
        <ve-radio v-else v-model="form.memberType" :list="dict.memberTypeEnum" @confirm="changeMemberTypeFn" />
      </ve-form-item>
      <template v-if="form.memberType == 1">
        <ve-form-item prop="clientId" required label="客户公司名称" :borderBottom="contentIsShow">
          <remote-select
            v-model="form.clientId"
            :label="form.clientName"
            type="member_clientInfo"
            :params="{
              oldId: form.clientId,
            }"
            @change="changeClientFn"
          />
        </ve-form-item>
      </template>
    </template>
    <!-- 企业用户 -->
    <template v-if="form.memberType == 1">
      <member-form-item
        prop="memberName"
        label="承租人"
        required
        :memeberType="1"
        :borderBottom="false"
        :memberInfo="memberInfo"
        labelTooltipContent="请在会员管理中添加企业承租人"
        :showUploadDriverBtn="showUploadDriverBtn"
        :showUploadIdCardBtn="showUploadIdCardBtn"
        @uploadDriverLicenseFn="uploadDriverLicenseFn"
        @uploadIdCardFn="uploadIdCardFn"
      >
        <!-- 选择了客户公司名称 -->
        <template v-if="form.clientId">
          <remote-select
            v-model="form.memberId"
            :label="form.memberName"
            :params="{ clientId: form.clientId, oldId: form.memberId }"
            type="member_list"
            @change="changeMemberInfo"
          />
        </template>
        <template v-else>
          <view class="disabled-select" @tap="noSelectClientFn">
            <view class="disabled-select_input">请先选择客户公司名称</view>
            <view class="disabled-select_arrow">
              <ve-icon name="arrow_right_2" size="32" />
            </view>
          </view>
        </template>
      </member-form-item>
    </template>
    <!-- 个人用户 -->
    <template v-if="form.memberType == 2">
      <member-form-item
        prop="memberName"
        label="承租人"
        required
        :borderBottom="false"
        :memeberType="2"
        :memberInfo="memberInfo"
        :showUploadDriverBtn="showUploadDriverBtn"
        :showUploadIdCardBtn="showUploadIdCardBtn"
        @uploadDriverLicenseFn="uploadDriverLicenseFn"
        @uploadIdCardFn="uploadIdCardFn"
      >
        <adaption-input :disabled="catchedMemberByPhone" v-model="form.memberName" :maxlength="30" @blur="mermberNameBlur" />
      </member-form-item>
      <ve-form-item prop="memberPhone" label="联系电话" required :borderBottom="contentIsShow">
        <!-- 选择手机号 -->
        <ve-picker-inline
          v-if="catchedPhoneList.length"
          v-model="form.memberId"
          placeholder="请选择"
          :range="catchedPhoneList"
          unit="arrowRight"
        ></ve-picker-inline>
        <ve-input v-else v-model="form.memberPhone" :maxlength="11" @clear="memberPhoneClearFn" @blur="memberPhoneInputFn" />
      </ve-form-item>
    </template>
    <ve-toast ref="toast" />
  </ve-card>
</template>
<script setup>
  import { ref, inject } from 'vue'
  import adaptionInput from './customer/adaption-input.vue'
  import memberFormItem from './customer/member-form-item.vue'
  import { getPhoneListByMemberName, findByPhoneAPI } from '@/api/order/order'

  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { serializeUrlParams } from '@/utils'

  const props = defineProps({
    mode: {
      type: String,
      default: '',
    },
  })

  // 接收 inject
  const form = inject('form')
  const dict = inject('dict')
  // 用户信息
  const memberInfo = ref({})
  // 是否显示驾驶证上传按钮
  const showUploadDriverBtn = ref(false)
  // 是否显示身份证明上传按钮
  const showUploadIdCardBtn = ref(false)
  // 切换客户类型
  const changeMemberTypeFn = () => {
    // 清空客户公司信息
    form.value.clientId = undefined
    form.value.clientName = undefined
    // 清空会员信息
    clearFormMembder()
  }
  // 切换企业
  const changeClientFn = (val, option) => {
    // 企业名称
    form.value.clientName = option.clientName
    // 清空会员信息
    clearFormMembder()
  }
  const memberPhoneFetching = ref(false)
  // 联系电话输入回调 13333333388
  let cachedPhone = ''
  // 手机号是否找到会员，找到则会员姓名不可输入
  const catchedMemberByPhone = ref(fasle)
  const memberPhoneInputFn = (phone) => {
    if (phone && /^[0-9]+$/.test(phone)) {
      // 忽略重复参数 befroe
      if (cachedPhone == phone) return
      cachedPhone = phone
      // 忽略重复参数 end
      form.value.memberPhone = phone
      memberPhoneFetching.value = true
      findByPhoneAPI({ phone: phone }).then(({ result }) => {
        memberPhoneFetching.value = false
        if (result) {
          catchedMemberByPhone.value = true
          updateFormMembder(result)
        } else {
          catchedMemberByPhone.value = false
          // 兼容情况
          // 输入了一个已有会员的手机号，自动填充承租人、证件号
          // 再次输入一个没有会员的手机号，清空承租人、证件号
          if (form.value.memberId) {
            updateFormMembder()
          }
          form.value.cardType = 0 // 证件类型，默认身份证
          form.value.memberPhone = phone
          // 清空客户企业id
          form.value.clientId = null
          showUploadDriverBtn.value = true
          showUploadIdCardBtn.value = true
        }
      })
    }
  }

  // 缓存会员姓名
  let cachedMemberName = form.value.memberName
  // 会员姓名是否找到会员，找到则手机号下拉框
  const catchedPhoneList = ref([])
  const mermberNameBlur = (value) => {
    console.log('🐳 > mermberNameBlur > value:', value)
    if (value == cachedMemberName) return
    cachedMemberName = value
    getPhoneListByMemberName({ memberName: value }).then((res) => {
      const result = res.result
      // 清空会员手机号值
      form.value.memberId = undefined
      form.value.memberPhone = undefined
      catchedPhoneList.value = resutl.map((it) => {
        return {
          value: it.id,
          label: it.phone,
        }
      })
    })
  }
  const mermberNameChange = () => {}

  // 等待手机号查询事件结束
  const waitMemberPhoneFetchingDone = (cb) => {
    watch(
      () => memberPhoneFetching.value,
      (newVal) => {
        if (!newVal) {
          cb && cb()
        }
      },
    )
  }

  // 清空
  const memberPhoneClearFn = () => {
    updateFormMembder()
  }

  // 没选择公司提示
  const toast = ref()
  const noSelectClientFn = () => {
    toast.value.show({
      title: '请先选择客户公司',
      type: 'error',
    })
  }

  // 切换会员
  const changeMemberInfo = (val, option) => {
    updateFormMembder(option)
  }

  // 清空 form 客户相关信息
  const clearFormMembder = () => {
    memberInfo.value = {}
    form.value.memberId = undefined
    form.value.memberPhone = undefined
    form.value.memberName = undefined
    form.value.cardType = undefined
    form.value.cardNumber = undefined
    form.value.driverFrontFileId = undefined
    form.value.driverReverseFileId = undefined
    form.value.idCardFrontFileId = undefined
    form.value.idCardReverseFileId = undefined
    showUploadDriverBtn.value = false
    showUploadIdCardBtn.value = false
  }

  // 更新 form 客户相关信息
  const updateFormMembder = (option = {}) => {
    memberInfo.value = option
    form.value.memberId = option.id
    form.value.memberPhone = option.phone
    form.value.memberName = option.memberName
    form.value.cardType = option.cardType
    form.value.cardNumber = option.cardNumber
    // 驾驶证正反面信息
    form.value.driverFrontFileId = option.driverFrontFileId
    form.value.driverReverseFileId = option.driverReverseFileId
    // 身份证明正反面信息
    form.value.idCardFrontFileId = option.idCardFrontFileId
    form.value.idCardReverseFileId = option.idCardReverseFileId
    // option 不为空
    if (option?.id) {
      showUploadDriverBtn.value = !form.value.driverFrontFileId || !form.value.driverReverseFileId
      showUploadIdCardBtn.value = !form.value.idCardFrontFileId || (form.value.cardType == 0 && !form.value.idCardReverseFileId)
    } else {
      showUploadDriverBtn.value = false
      showUploadIdCardBtn.value = false
    }
  }

  // 上传驾驶证点击
  const uploadDriverLicenseFn = () => {
    let url = '/pages/order/upload-driver-license?'
    const param = {
      driverFrontFileId: form.value.driverFrontFileId,
      driverReverseFileId: form.value.driverReverseFileId,
      autoUpload: false,
    }
    if (props.mode == 'edit') {
      param.memberId = form.value.memberId
    }
    url += serializeUrlParams(param)
    uni.navigateTo({ url: url })
  }

  // 上传身份证明点击
  const uploadIdCardFn = () => {
    let url = '/pages/order/upload-id-card?'
    const param = {
      cardType: form.value.cardType,
      idCardFrontFileId: form.value.idCardFrontFileId,
      idCardReverseFileId: form.value.idCardReverseFileId,
      autoUpload: false,
    }
    if (props.mode == 'edit') {
      param.memberId = form.value.memberId
    }
    url += serializeUrlParams(param)
    uni.navigateTo({ url: url })
  }

  onLoad(() => {
    // 车型选择完成
    uni.$on('uploadDriverLicenseOk', (option) => {
      const { driverFrontFileId, driverReverseFileId } = option
      // 更新驾驶证正反面 id
      form.value.driverFrontFileId = driverFrontFileId
      form.value.driverReverseFileId = driverReverseFileId
    })
    uni.$on('uploadIdCardOk', (option) => {
      const { idCardFrontFileId, idCardReverseFileId, cardType } = option
      // 更新身份证明正反面 id
      form.value.idCardFrontFileId = idCardFrontFileId
      form.value.idCardReverseFileId = idCardReverseFileId
      // 更新证件类型
      form.value.cardType = cardType
    })
  })
  onUnload(() => {
    uni.$off('carModelOk')
  })

  // 更新是否显示上传驾驶证按钮
  const updateUploadDriverBtnStatus = (show) => {
    showUploadDriverBtn.value = show
  }
  // 更新是否显示上传身份证明按钮
  const updateUploadIdCardBtnStatus = (show) => {
    showUploadIdCardBtn.value = show
  }
  // 更新memberInfo
  const updateMemberInfo = (info) => {
    memberInfo.value = info
  }
  defineExpose({
    updateUploadDriverBtnStatus,
    updateUploadIdCardBtnStatus,
    memberPhoneFetching,
    waitMemberPhoneFetchingDone,
    updateMemberInfo,
  })
</script>
<style lang="less" scoped>
  .memeber-type-form {
    /deep/ .ve-form-item__body__right {
      display: flex;
      align-items: center;
    }
  }
  .disabled-select {
    position: relative;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    &_input {
      font-size: 30rpx;
      font-weight: 400;
      line-height: 44rpx;
      text-align: right;
      flex: 1;
      color: #cdced0;
    }
    &_arrow {
      flex-shrink: 0;
      margin-left: 10rpx;
      display: flex;
      align-items: center;
    }
  }
  .client-member {
    /deep/ .member-name-tag {
      margin-right: 7rpx;
    }
  }
</style>
